using System;
using UnityEngine;

namespace DanielSig.UnityExtensions
{
	public static class XTransform
	{
		public static Vector3 ToLocalPoint(this Transform transform, Vector3 point)
		{
			return transform.InverseTransformPoint(point);
		}
		public static Vector3 ToLocalDirection(this Transform transform, Vector3 direction)
		{
			return transform.InverseTransformDirection(direction);
		}
		public static Plane ToLocalPlane(this Transform transform, Plane plane)
		{
			return new Plane(transform.InverseTransformDirection(plane.normal), -plane.GetDistanceToPoint(transform.position));
		}
		
		public static Vector3 ToGlobalPoint(this Transform transform, Vector3 point)
		{
			return transform.TransformPoint(point);
		}
		public static Vector3 ToGlobalDirection(this Transform transform, Vector3 direction)
		{
			return transform.TransformDirection(direction);
		}
		public static Plane ToGlobalPlane (this Transform transform, Plane plane)
		{
			Vector3 normal = transform.TransformDirection(plane.normal);
			return new Plane(normal, -(normal.Dot(transform.position) + plane.distance));
			//return new Plane(normal, normal.Dot(transform.TransformPoint(plane.normal * plane.distance)));
		}
		public static Transform[] GetChildren(this Transform transform)
		{
			int childCount = transform.childCount;
			Transform[] children = new Transform[childCount];
			for (int i = 0; i < childCount; i++)
			{
				children[i] = transform.GetChild(i);
			}
			return children;
		}
		public static Rigidbody GetAbsRigidbody(this Transform transform)
		{
			return transform.rigidbody ?? (transform.parent ? transform.parent.GetAbsRigidbody() : null);
		}
		public static Vector3 GetForward(this Transform transform, float distance)
		{
			return transform.position + transform.forward * distance;
		}
		public static Vector3 GetRight(this Transform transform, float distance)
		{
			return transform.position + transform.right * distance;
		}
		public static Vector3 GetUp(this Transform transform, float distance)
		{
			return transform.position + transform.up * distance;
		}
		public static Vector3 GetPosition(this Transform transform, float right, float up, float forward)
		{
			return new Vector3(right, up, forward).From(transform);
		}
		public static Vector3 GetPosition(this Transform transform, Vector3 localPosition)
		{
			return localPosition.From(transform);
		}
		public static Transform GetGrandParent(this Transform transform)
		{
			Transform t = transform.transform;
			while(t.parent) t = t.parent;
			return t;
		}
	}
}

